package com.previewlibrary;

import com.previewlibrary.utils.SystemUtils;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.Surface;
import ohos.agp.graphics.SurfaceOps;
import ohos.agp.utils.Color;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.media.common.Source;
import ohos.media.player.Player;

import uk.co.senab2.photoview2.log.LogManager;

/**
 * GPVideoPlayerAbility.
 *
 * @author author
 * @version version
 */
public class GPVideoPlayerAbility extends Ability {
    /**
     * VIDEO_URI.
     */
    public static final String VIDEO_URI = "url";
    private static final String TAG = "PreViewVideoAbility";
    private Player player;
    private SurfaceProvider surfaceProvider;
    private String path;
    private boolean isBackground;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_gpvideo_player);
        WindowManager.getInstance().getTopWindow().get().setTransparent(true);
        getWindow().setStatusBarColor(Color.TRANSPARENT.getValue());
        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS);
        path = intent.getStringParam(VIDEO_URI);
        surfaceProvider = (SurfaceProvider) findComponentById(ResourceTable.Id_gpVideo);
        surfaceProvider.pinToZTop(false);
        surfaceProvider.getSurfaceOps().get().addCallback(new VideoSurfaceCallback());
        player = new Player(this);
        player.setPlayerCallback(new VideoPlayerCallback());
    }

    private void playLocalFile(Surface surface) {
        player.setSource(new Source(path));
        player.setVideoSurface(surface);
        player.setPlayerCallback(new VideoPlayerCallback());
        player.prepare();
        // surfaceProvider.setTop(0);
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
        if (this.isBackground) {
            player.play();
        }
        this.isBackground = false;
    }

    @Override
    protected void onBackground() {
        super.onBackground();
        this.isBackground = true;
        if (player != null) {
            player.pause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        player.stop();
        player.release();
    }

    private class VideoSurfaceCallback implements SurfaceOps.Callback {
        @Override
        public void surfaceCreated(SurfaceOps surfaceOps) {
            if (surfaceProvider.getSurfaceOps().isPresent()) {
                Surface surface = surfaceProvider.getSurfaceOps().get().getSurface();
                playLocalFile(surface);
            }
        }

        @Override
        public void surfaceChanged(SurfaceOps surfaceOps, int i, int i1, int i2) {
        }

        @Override
        public void surfaceDestroyed(SurfaceOps surfaceOps) {
        }
    }

    private class VideoPlayerCallback implements Player.IPlayerCallback {
        @Override
        public void onPrepared() {
            LogManager.getLogger().i(TAG, "VideoPlayerCallback onPrepared");
            player.play();
        }

        @Override
        public void onMessage(int i, int i1) {
            LogManager.getLogger().i(TAG, "VideoPlayerCallback onMessage i= " + i + " i1 =" + i1);
        }

        @Override
        public void onError(int i, int i1) {
            LogManager.getLogger().i(TAG, "VideoPlayerCallback onError i= " + i + " i1 =" + i1);
        }

        @Override
        public void onResolutionChanged(final int width, final int height) {
            LogManager.getLogger().i(TAG, "VideoPlayerCallback onResolutionChanged width= " + width + " height =" + height);
            GPVideoPlayerAbility.this.getUITaskDispatcher().syncDispatch(() -> {
                float proportion = Float.valueOf(width) / Float.valueOf(height);
                int ww = width;
                int hh = height;
                int displayWidthInPx = SystemUtils.getDisplayWidthInPx(GPVideoPlayerAbility.this);
                int displayHightInPx = SystemUtils.getDisplayHightInPx(GPVideoPlayerAbility.this);
                if (ww > displayWidthInPx || hh > displayHightInPx) {
                    if (ww > displayWidthInPx) {
                        ww = displayWidthInPx;
                        hh = (int) (ww / proportion);
                    }
                    if (hh > displayHightInPx) {
                        hh = displayHightInPx;
                        ww = (int) (proportion * hh);
                    }
                }
                ComponentContainer.LayoutConfig layoutConfig = surfaceProvider.getLayoutConfig();
                layoutConfig.width = ww;
                layoutConfig.height = hh;
                surfaceProvider.setLayoutConfig(layoutConfig);
            });
        }

        @Override
        public void onPlayBackComplete() {
            terminateAbility();
        }

        @Override
        public void onRewindToComplete() {
        }

        @Override
        public void onBufferingChange(int i) {
        }

        @Override
        public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) {
        }

        @Override
        public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) {
        }
    }

    /***
     * 启动播放视频
     * @param   context context
     * @param  url url
     * ***/
    public static void startAbility(Context context, String url) {
        Intent intent = new Intent();
        Operation opt = new Intent
                .OperationBuilder()
                .withBundleName(context.getBundleName())
                .withAbilityName(GPVideoPlayerAbility.class.getCanonicalName())
                .build();
        intent.setOperation(opt);
        intent.setParam(VIDEO_URI, url);
        context.startAbility(intent, 0);
    }
}
